package com.cmccgz.baselibrary.base;

import android.Manifest;
import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.provider.Settings;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;

import java.util.ArrayList;
import java.util.List;

/**
 * @author: Huang
 * @Descripion:
 * @date 2017/5/23 17:34
 */

public class PermissionUtils {

    public static final int REQUEST_CODE_ASK_PERMISSIONS = 0x234;
    public static final int REQUEST_CODE_ASK_BASE_PERMISSIONS = 0X345;
    public static final int REQUEST_CODE_ASK_CAMERA_PERMISSIONS = 0X333;

    public static void askPermission(Activity activity,int requestCode, PermissionAskCallback callback, String... permissions){
        List<String> permissionNeed = new ArrayList<String>();
        for (int i = 0;i<permissions.length;i++){
            int isHasPermission = ContextCompat.checkSelfPermission(activity, permissions[i]);
            if (isHasPermission!= PackageManager.PERMISSION_GRANTED){
                permissionNeed.add(permissions[i]);
            }
        }
        if (permissionNeed.size()>0){
            ActivityCompat.requestPermissions(activity,permissionNeed.toArray(new String[permissionNeed.size()]),requestCode);
        }else {
            if (callback!=null) {
                callback.hasPermissionDoNext();
            }
        }
    }

    public static void askPermission(Fragment fragment, int requestCode,PermissionAskCallback callback, String... permissions){
        List<String> permissionNeed = new ArrayList<String>();
        for (int i = 0;i<permissions.length;i++){
            int isHasPermission = ContextCompat.checkSelfPermission(fragment.getActivity(), permissions[i]);
            if (isHasPermission!= PackageManager.PERMISSION_GRANTED){
                permissionNeed.add(permissions[i]);
            }
        }
        if (permissionNeed.size()>0){
            fragment.requestPermissions(permissionNeed.toArray(new String[permissionNeed.size()]),requestCode);
        }else {
            if (callback!=null) {
                callback.hasPermissionDoNext();
            }
        }
    }

    /**
     * 处理用户拒绝授权后的提示框
     * @param context
     * @param cancelListener 必传，不能为空，取消按钮点击事件
     * @param permissions 权限字符串
     */
    private static void handleDialog(Activity context,DialogInterface.OnClickListener cancelListener, String... permissions) {
        PackageManager packageManager;
        ApplicationInfo applicationInfo;
        try {
            packageManager = context.getApplicationContext().getPackageManager();
            applicationInfo = packageManager.getApplicationInfo(context.getPackageName(), 0);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
            applicationInfo = null;
            packageManager = null;
        }
        String appName;
        if (packageManager!=null&&applicationInfo!=null){
            appName = packageManager.getApplicationLabel(applicationInfo).toString();
        }else {
            appName = "";
        }

        String message = "在设置-应用-"+appName+"-权限中开启\n\n";
        for (String permission:permissions) {
            switch (permission) {                                          //处理提示内容
                case Manifest.permission.ACCESS_COARSE_LOCATION:
                case Manifest.permission.ACCESS_FINE_LOCATION:
                    message += "位置信息权限\n";
                    break;
                case Manifest.permission.READ_EXTERNAL_STORAGE:
                case Manifest.permission.WRITE_EXTERNAL_STORAGE:
                    message += "储存空间权限\n";
                    break;
                case Manifest.permission.CALL_PHONE:
                case Manifest.permission.READ_PHONE_STATE:
                    message += "拨打管理通话权限\n";
                    break;
                case Manifest.permission.READ_SMS:
                    message += "短信读取权限\n";
                    break;
                case Manifest.permission.READ_CONTACTS:
                    message += "读取联系人权限\n";
                    break;
                case Manifest.permission.CAMERA:
                    message += "拍照权限\n";
                    break;
                default:
                    message += "相关权限\n";
                    break;
            }
        }
        message += "\n以正常使用"+appName+"功能";
        showMessage(message, cancelListener, context);
    }

    /**
     * 弹框
     * @param message
     * @param cancelListener
     * @param context
     */
    private static void showMessage(String message, DialogInterface.OnClickListener cancelListener, final Activity context) {
        new AlertDialog.Builder(context)
                .setTitle("权限申请")
                .setMessage(message)
                .setCancelable(false)
                .setPositiveButton("去设置", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        Uri uri = Uri.parse("package:"+context.getPackageName());
                        Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS,uri);
                        context.startActivity(intent);
                        context.finish();
                    }
                })
                .setNegativeButton("取消", cancelListener)
                .create()
                .show();
    }

    /**
     * 处理回调结果，必须在activity的onRequestPermissionsResult方法中调用，用于处理系统提示框的结果回调
     * @param permissions 请求的字符串数组
     * @param grantResults 返回权限判断结果，PackageManager.PERMISSION_GRANTED为授权成功，PackageManager.PERMISSION_DENIED为授权失败
     * @param activity
     * @param callback 回调，授权成功后调用此方法，用于处理授权之后的相应操作
     * @param cancelListener 必传，不能为空，取消按钮点击事件
     */
    public static void handlePermissionRequest(
            String[] permissions, int[] grantResults,
            Activity activity, PermissionAskCallback callback,
            DialogInterface.OnClickListener cancelListener) {
        if (permissions.length==1) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                if (callback!=null) {
                    callback.hasPermissionDoNext();
                }
            } else if (grantResults[0] == PackageManager.PERMISSION_DENIED) {
                handleDialog(activity,cancelListener, permissions[0]);
            }
        }else if (permissions.length>1){
            List<String> permissionNeed = new ArrayList<String>();
            for (int i = 0;i<grantResults.length;i++){
                if (grantResults[i] != PackageManager.PERMISSION_GRANTED){
                    permissionNeed.add(permissions[i]);
                }
            }
            if (permissionNeed.size()==0){
                if (callback!=null) {
                    callback.hasPermissionDoNext();
                }
            }else if (permissionNeed.size()>0){
                handleDialog(activity,cancelListener,permissionNeed.toArray(new String[permissionNeed.size()]));
            }
        }
    }

    /**
     * 回调接口
     */
    public interface PermissionAskCallback {
        void hasPermissionDoNext();
    }
}
